package com.cloudxingkong.dianyinke.NewTeacher.Ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.MultiSpinnerT;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.PhotoUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.UploadUtils;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;

import org.xutils.http.RequestParams;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;


/**
 * 正在上传
 */
public class UploadingWork extends AppCompatActivity implements View.OnClickListener, MultiSpinnerT.MultiSpinnerListener {

    private static final String TAG = UploadingWork.class.getSimpleName();



    private RelativeLayout uling_cover;
    private EditText et_title, et_price, et_address, et_self;
    private ImageView iv_cover;
    private ListView lv;
    private String title, price, address, self, lessonID;
    private String picPath = "";
    private String spinnerSelectedItem = "";
    /**SharedPreferences*/
    private SharedPreferences sharedPreferences;
    private ProgressDialog progressDialog;
    private boolean flag = false;

    private static final int RESULT_CODE = 666;

    private static int UPDATE = -1;

    private ArrayList<String> pathList;
    private static final int REQUEST_IMAGE=2;
    private Spinner kemuSpinner;
    private MultiSpinnerT multiSpinner;
    private List<String> labels;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uploading_work);
        init();

        /** 设置封面*/
        uling_cover.setOnClickListener(UploadingWork.this);

    }

    private void updateLesson() {
        String lessonTitle = sharedPreferences.getString("lessonTitle", "");
        String lessonPrice = sharedPreferences.getString("lessonPrice", "");
        String lessonAddr = sharedPreferences.getString("lessonAddr", "");
        String lessonNote = sharedPreferences.getString("lessonNote", "");
        String lessonLabel = sharedPreferences.getString("lessonLabel", "");
        lessonID = sharedPreferences.getString("lessonID", "");
        et_title.setText(lessonTitle);
        et_price.setText(lessonPrice);
        et_address.setText(lessonAddr);
        et_self.setText(lessonNote);
    }

    private void init() {
        uling_cover = (RelativeLayout) findViewById(R.id.uling_cover);
        et_title = (EditText) findViewById(R.id.uling_et_title);
        et_price = (EditText) findViewById(R.id.uling_et_price);
        et_address = (EditText) findViewById(R.id.uling_et_address);
        et_self = (EditText) findViewById(R.id.uling_et_self);
        iv_cover = (ImageView) findViewById(R.id.uling_ivcover);
        kemuSpinner = (Spinner) findViewById(R.id.uling_kemu_spinner);

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
                android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item,
                Constans.VIDEO_LABEL);
        kemuSpinner.setAdapter(arrayAdapter);

        multiSpinner = (MultiSpinnerT) findViewById(R.id.uling_multispinner);
        labels = new ArrayList<>();
        labels.add("一对一教学");
        labels.add("随时退");
        labels.add("包教会");
        labels.add("氛围轻松");
        labels.add("老师和蔼");
        multiSpinner.setItems(labels, "选择标签", this);

        /** 取出存在SharedPreferences中的sessionID*/
        sharedPreferences = getSharedPreferences("data_dyk", 0);

        String updataLesson = getIntent().getStringExtra("updataLesson");
        if (updataLesson!=null&&updataLesson.equals("101")){
            updateLesson();
            UPDATE=0;
        }
    }

    public void back(View view) {
        switch (view.getId()){
            case R.id.uwing_back:
                finish();
                break;
            case R.id.uwing_queren:
                if (
                        TextUtils.isEmpty(et_address.getText())||
                        TextUtils.isEmpty(et_self.getText())||
                        TextUtils.isEmpty(et_price.getText())||
                        TextUtils.isEmpty(et_title.getText())) {
                    Toast.makeText(this,"您的课程尚有未完善的部分\n请补充后提交~",Toast.LENGTH_SHORT).show();
                }else {
                    if (spinnerSelectedItem.equals("")) {
                        Toast.makeText(UploadingWork.this, "尚未选择标签~", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Log.e("test", "上传课程  " + " - " + picPath);
                    if (picPath.equals("")) {
                        Toast.makeText(UploadingWork.this, "请选择课程封面", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    progressDialog = ProgressDialog.show(this, null, "正在上传....", true, false);

                    title = et_title.getText().toString();
                    price = et_price.getText().toString();
                    address = et_address.getText().toString();
                    self = et_self.getText().toString();
                    String kemu = kemuSpinner.getSelectedItem().toString();


                    /** sharedPerfrences读取数据*/
                    String sessionID = CookieHelper.getSessionID(sharedPreferences);
                    /** 读取经纬度*/
                    String longitude = sharedPreferences.getString("longitude", "");
                    String latitude = sharedPreferences.getString("latitude", "");


                    Log.e("test", "上传课程 ~ \n标题 " + title + "\n价格 " + price + "\n地址 " + address + "\n个人补充 " + self +
                            "\n标签 " + spinnerSelectedItem + "\n经度 " + longitude + "\n维度 " + latitude);
                    final String upLoadUrl = ThisUri.SERVER_YUMING + ThisUri.UPLOAD_WORK;

                    final RequestParams params = new RequestParams(upLoadUrl);
                    params.addHeader("cookie", sessionID);
                    params.setMultipart(true);

                    //为0是更新课程
                    if (UPDATE == 0) {
                        params.addBodyParameter("id", lessonID);
                    }
                    if (!picPath.equals("")) {
                        File file = new File(picPath);
                        params.addBodyParameter("coverpic", file);
                    }
                    params.addBodyParameter("addr", address);
                    params.addBodyParameter("price", price);
                    params.addBodyParameter("note", self);
                    params.addBodyParameter("title", title);
                    params.addBodyParameter("label", spinnerSelectedItem);
                    params.addBodyParameter("subject", kemu);
                    params.addBodyParameter("posx", longitude);
                    params.addBodyParameter("posy", latitude);

                    UploadUtils.postData(params, new UploadUtils.UploadCallback() {
                        @Override
                        public void onFinish(String state) {
                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            msg.obj = state;

                            handler.sendMessage(msg);
                        }
                    });

                }
                break;
        }
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                String state= (String) msg.obj;
                Log.e("test","上传课程结果 "+state);
                HashMap<String, Object> jsonFromLogin = LoginJsonUtils.getJsonFromLogin(state);
                flag= (boolean) jsonFromLogin.get("success");

                if (flag) {
                    Toast.makeText(UploadingWork.this, "上传课程成功！", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                    setResult(RESULT_CODE);
                    finish();
                }else{
                    Toast.makeText(UploadingWork.this,"上传失败！",Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            }
        }
    };

    @Override
    public void onClick(View v) {

        int maxNum=1;
        Intent intent=new Intent(UploadingWork.this,MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA,true);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT,maxNum);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        if (pathList != null && pathList.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST,pathList);
        }
        startActivityForResult(intent, REQUEST_IMAGE);

    }

    /**
     * 隐式意图返回的结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {   //resultCode=-1   requestCode=1 data = null
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == Activity.RESULT_OK) {
                pathList=data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (String s : pathList) {
                    PhotoUtils photoUtils3 = new PhotoUtils();
                    PhotoUtils.CompressOptions options3=new PhotoUtils.CompressOptions();
                    options3.uri=Uri.fromFile(new File(s));
                    Bitmap bitmap3 = photoUtils3.compressFromUri(this, options3);

                    iv_cover.setImageBitmap(bitmap3);
                    picPath=s;
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 选择标签
     * @param selected
     */
    @Override
    public void onItemsSelected(boolean[] selected) {
        if (!spinnerSelectedItem.equals("")) {
            spinnerSelectedItem = "";
        }
        for (int i = 0; i < selected.length; i++) {
            if (selected[i]) {
                spinnerSelectedItem += labels.get(i) + ",";
            }
        }
        Log.e("test", "选择的标签 : " + spinnerSelectedItem);
    }
}
